package com.qf.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * @Author:zhangyang
 * @Date: 11:26
 * @Version 1.0
 */
public class JdbcUtils {
    private static DataSource dataSource ;
    //创建本地线程对象
    private static  ThreadLocal<Connection> t
            = new ThreadLocal<Connection>() ;  //里面空的

    static{

        try{
            //创建属性集合类对象
            Properties prop = new Properties() ;
            //读取src下面的配置文件
            InputStream inputStream = JdbcUtils.class.getClassLoader().
                    getResourceAsStream("druid.properties");
            //加载配置文件的内容
            prop.load(inputStream);
            //获取数据源
            dataSource = DruidDataSourceFactory.createDataSource(prop) ;
//            System.out.println(dataSource);
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    //获取数据源
    public static DataSource getDataSource(){
        return  dataSource;
    }

    //获取连接对象
    public static Connection getConnction(){
        //从数据源中获取

       /* try {
            Connection conn = dataSource.getConnection();
            return conn ;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null ;*/

        Connection conn = null ;
        try{
            //从本地线程中获取Connection
            conn = t.get();
            //如果当前conn为null,从连接池获取Connection
            if(conn==null){
                conn = dataSource.getConnection() ;
                //将从连接池获取到Connection对象绑定到线程中
                t.set(conn);
                return conn ;
            }
        }catch (SQLException e){
            e.printStackTrace();
        }
        return null ;
    }

    //关闭资源
    public static void close(ResultSet rs, Statement stmt, Connection conn){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if(stmt!=null){
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if(conn!=null){
            try {
                conn.close(); //归还到连接池中
            } catch (SQLException e) {
                e.printStackTrace();
            }finally {
                //从本地线程ThreadLocal移除:解绑
                t.remove();
            }
        }
    }

    public static void close( Statement stmt,Connection conn){
        close(null,stmt,conn);
    }

    public static void main(String[] args) {
      //从连接池中获取连接对象
        Connection connction = JdbcUtils.getConnction();
        System.out.println(connction);

        DataSource dataSource = JdbcUtils.getDataSource();
        System.out.println(dataSource);
    }
}
